package com.chenwc.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.chenwc.enumeration.TranslateSoftware;
import com.chenwc.util.fileutil.ReadFile;
import com.chenwc.util.fileutil.WriteFile;
import com.chenwc.util.fileutil.jsonfile.JsonFileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * @author chenwc
 * @package com.chenwc.util
 * @project wso2-sinicization
 * @date 2024/5/25
 */
public class TranslateJsonFile {

    private static final Logger log = LoggerFactory.getLogger(TranslateJsonFile.class);

    /**
     * 翻译所有json文件
     *
     * @param wso2FilePath      wso2文件路径
     * @param translateSoftware 翻译软件
     */
    public static void translateAllJsonFile(String wso2FilePath, TranslateSoftware translateSoftware) {
        List<String> filelist = Util.searchEnJsonFileList(wso2FilePath);
        log.info("filelist size: {}", filelist.size());
        log.info("filelist: {}", JSON.toJSONString(filelist, JSONWriter.Feature.WriteMapNullValue));
        HashMap<String, String> terminology = LoadTerminology.getTerminology();
        try {
            for (String file : filelist) {
                File jsonFile = new File(file);
                JSONObject jsonObject = JSON.parseObject(ReadFile.readFile(jsonFile));
                JSONObject rst = JsonFileUtil.recursionJsonObject(jsonObject, terminology, translateSoftware);
                if (file.contains("en-US") && "en-US.json".equals(jsonFile.getName())){
                    // 写入zh-CN.json文件
                    String newFilePath = file.substring(0, file.lastIndexOf("\\")) + "\\"
                            + jsonFile.getName().replace("en-US", "zh-CN");
                    WriteFile.write(new File(newFilePath), rst.toJSONString());
                }
                else if (file.contains("en-US") && !"en-US.json".equals(jsonFile.getName())){
                    // 写入json文件
                    String newFilePath = file.replace("en-US", "zh-CN");
                    WriteFile.write(new File(newFilePath), rst.toJSONString());
                }
                else {
                    // 写入zh.json文件
                    String newFilePath = file.substring(0, file.lastIndexOf("\\")) + "\\"
                            + jsonFile.getName().replace("en", "zh");
                    WriteFile.write(new File(newFilePath), rst.toJSONString());
                }

            }
        } catch (Exception e) {
            log.error("translateAllJsonFile error: {}", e.getMessage());
        }

    }
}
